﻿using System;
using System.Collections.Generic;
using System.Linq;
using Orchard.ContentManagement;
using Orchard.DisplayManagement;
using Orchard.Localization;
using Orchard.Projections.Descriptors.Layout;
using Orchard.Projections.Models;
using Orchard.Projections.Services;

namespace Contrib.Projections.Providers.Layouts {
    public class SeparatorLayout : ILayoutProvider {
        private readonly IContentManager _contentManager;
        protected dynamic Shape { get; set; }

        public SeparatorLayout(IShapeFactory shapeFactory, IContentManager contentManager) {
            _contentManager = contentManager;
            Shape = shapeFactory;
            T = NullLocalizer.Instance;
        }

        public Localizer T { get; set; }

        public void Describe(DescribeLayoutContext describe) {
            describe.For("Html", T("Html"),T("Html Layouts"))
                .Element("Separator", T("Separator"), T("Organizes content items separated by an element."),
                    DisplayLayout,
                    RenderLayout,
                    "SeparatorLayout"
                );
        }

        public LocalizedString DisplayLayout(LayoutContext context) {
            string separator = context.State.Separator;

            return T("List of elements splitted by a separator");
        }

        public dynamic RenderLayout(LayoutContext context, IEnumerable<LayoutComponentResult> layoutComponentResults) {
            string separator = context.State.Separator;

            IEnumerable<dynamic> shapes;
            if(context.LayoutRecord.Display == (int) LayoutRecord.Displays.Content) {
                shapes = layoutComponentResults.Select(x => _contentManager.BuildDisplay(x.ContentItem, context.LayoutRecord.DisplayType));
            }
            else {
                shapes = layoutComponentResults.Select(x => x.Properties);
            }

            return Shape.Split(Separator: separator, Items: shapes);
        }
    }
}